package com.kma.summer2012.server.proxy;

import com.kma.summer2012.dao.CrumbsRequestsStateDAO;
import com.kma.summer2012.factory.DAOFactory;
import com.kma.summer2012.factory.SpringBeansFactory;
import com.kma.summer2012.model.*;
import com.kma.summer2012.shared.model.*;

import java.text.SimpleDateFormat;
import java.util.*;

public class Proxy {
    private static Proxy instance;

    private Proxy() {
    }

    public static Proxy getInstance() {
        if (instance == null) {
            instance = new Proxy();
        }
        return instance;
    }

    public UICrumbsUser createFromUser(CrumbsUser user) {
        UICrumbsUser uiCrumbsUser = new UICrumbsUser();
        uiCrumbsUser.setUserId(user.getUserId());
        uiCrumbsUser.setLogin(user.getLogin());
        uiCrumbsUser.setPassword(user.getPassword());
        uiCrumbsUser.setPosition(user.getCrumbsPosition().getName());
        uiCrumbsUser.setPositionId(user.getCrumbsPosition().getId());
        uiCrumbsUser.setSurnmNmSecondnm(user.getSurnmNmSecondnm());
        return uiCrumbsUser;
    }

    public CrumbsUser createUser(UICrumbsUser uiuser) {
        CrumbsUser user = new CrumbsUser();
        user.setUserId(uiuser.getUserId());
        user.setLogin(uiuser.getLogin());
        CrumbsPosition position = new CrumbsPosition();
        position.setName(uiuser.getPosition());
        position.setId(uiuser.getPositionId());
        user.setCrumbsPosition(position);
        return user;
    }

    public UICrumbsClient createFromClient(CrumbsClient client) {
        UICrumbsClient newCrumbsClient = new UICrumbsClient();
        newCrumbsClient.setId(client.getId());
        newCrumbsClient.setName(client.getName());
        newCrumbsClient.setAdress(client.getAdress());
        newCrumbsClient.setMail(client.getMail());
        return newCrumbsClient;
    }

    public CrumbsClient createClient(UICrumbsClient client) {
        CrumbsClient newCrumbsClient = new CrumbsClient();
        newCrumbsClient.setId(client.getId());
        newCrumbsClient.setName(client.getName());
        newCrumbsClient.setAdress(client.getAdress());
        newCrumbsClient.setMail(client.getMail());
        return newCrumbsClient;
    }

    public CrumbsRequest createRequest(UICrumbsRequest request) {
        final CrumbsRequest crumbsRequest = new CrumbsRequest();

        crumbsRequest.setDateOfCreationCustom(request.getDateOfCreation());

        CrumbsClient client = new CrumbsClient();
        client.setId(request.getUicrumbsClient().getId());
        client.setAdress(request.getUicrumbsClient().getAdress());
        client.setName(request.getUicrumbsClient().getName());
        client.setMail(request.getUicrumbsClient().getMail());

        crumbsRequest.setCrumbsClient(client);
        Set<CrumbsRequestAndWork> workSet = new HashSet<CrumbsRequestAndWork>();


        /*if (request.getUicrumbsWorkItems().size() > 0) {
            for (short i : request.getUicrumbsWorkItems().keySet()) {
                CrumbsRequestAndWork tmp = new CrumbsRequestAndWork();
                tmp.setCrumbsRequest(crumbsRequest);
                tmp.setAmountOfWork(i);
                CrumbsCatalogOfWork t;
                DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
                CrumbsCatalogOfWorkDAO dao = (CrumbsCatalogOfWorkDAO) factory.getCrumbsCatalogOfWorkDAO();
                try {
                    t = dao.getById(request.getUicrumbsWorkItems().get(i).getId());
                } catch (SQLException e) {
                    throw new CrumbsUniversalException("Wrong Work", e);
                }
                tmp.setCrumbsCatalogOfWork(t);
                t.getCrumbsRequestAndWorks().add(tmp);
                try {
                    dao.update(t);
                } catch (SQLException e) {
                    throw new CrumbsUniversalException("Wrong Work", e);
                }
                workSet.add(tmp);
            }
        }  */
        if (request.getRequestInfo() != null || !request.getRequestInfo().equals(""))
            crumbsRequest.setRequestInfo(request.getRequestInfo());
        else crumbsRequest.setRequestInfo(request.getRequestInfo());

        if (request.getActualTimeOfWork() != null) crumbsRequest.setActualTimeOfWork(request.getActualTimeOfWork());

        //todo query for state
        DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
        CrumbsRequestsStateDAO state = (CrumbsRequestsStateDAO) factory.getCrumbsRequestsStateDAO();
        try {
            crumbsRequest.setCrumbsRequestsState(state.findByName(request.getState().toString()));

        } catch (Exception e) {
            e.printStackTrace();
        }

        return crumbsRequest;

    }

    public UICrumbsRequest createFromRequest(CrumbsRequest request) {
        UICrumbsRequest crumbsRequest = new UICrumbsRequest();
        crumbsRequest.setId(request.getId());
        crumbsRequest.setState(request.getCrumbsRequestsState().getState());
        crumbsRequest.setStateId(request.getCrumbsRequestsState().getId());
        String DATE_FORMAT = "dd/MM/yyyy HH:mm";
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        crumbsRequest.setDateOfCreation(sdf.format(request.getDateOfCreation()));
        crumbsRequest.setRequestInfo(request.getRequestInfo());
        UICrumbsUser uiEngineer = new UICrumbsUser();
        Set<CrumbsUser> engineers = request.getCrumbsUsers();
        if (!(engineers.isEmpty())) {
            uiEngineer = this.createFromUser(engineers.iterator().next());
            crumbsRequest.setEngineer(uiEngineer);
        }

        Set<UICrumbsDateAndTime> dateTimeSet = new HashSet();
        for (CrumbsDateAndTime dt : request.getCrumbsDateAndTimes()) {
            dateTimeSet.add(Proxy.getInstance().createFromCumbsDateAndTime(dt));
        }
        crumbsRequest.setUicrumbsDateAndTimes(dateTimeSet);

        Map<UICrumbsWorkItem, Short> workItemSet = new HashMap<UICrumbsWorkItem, Short>();
        for (CrumbsRequestAndWork work : request.getCrumbsRequestAndWorks()) {
            workItemSet.put(Proxy.getInstance().createFromCatalogOfWorks(work.getCrumbsCatalogOfWork()), work.getAmountOfWork());
        }
        crumbsRequest.setUicrumbsWorkItems(workItemSet);

        crumbsRequest.setUicrumbsClient(new UICrumbsClient(request.getCrumbsClient().getId(),
                request.getCrumbsClient().getName(), request.getCrumbsClient().getAdress(), request.getCrumbsClient().getMail()));

        crumbsRequest.setActualTimeOfWork(request.getActualTimeOfWork());
        Set<UIComment> comments = new HashSet<UIComment>();
        for (CrumbsProcessHistory c : request.getCrumbsProcessHistories()) {
            UIComment n = new UIComment();
            n.setId(c.getId());
            n.setrequestId(c.getCrumbsRequest().getId());
            n.setComment(c.getCommentText());
            n.setCommentDate(c.getFixedDate().toString());
            n.setCommenter(Proxy.getInstance().createFromUser(c.getCrumbsUserBySenderId()));
            n.setReciever(Proxy.getInstance().createFromUser(c.getCrumbsUserByRecieverId()));
            comments.add(n);
        }
        crumbsRequest.setUicrumbsComments(comments);

        return crumbsRequest;


    }

    public UICrumbsWorkItem createFromCatalogOfWorks(CrumbsCatalogOfWork work) {
        UICrumbsWorkItem uiWork = new UICrumbsWorkItem();
        uiWork.setId(work.getId());
        if (work.getCrumbsCatalogOfWork() == null) {
            uiWork.setParentId(0);
        } else {
            uiWork.setParentId(work.getCrumbsCatalogOfWork().getId());
        }
        uiWork.setRuntime(work.getRuntime());
        //do not checked!!!
        List<String> toolsNames = new ArrayList<String>();
        if (work.getCrumbsCatalogOfTools() != null) {
            for (CrumbsCatalogOfTools tool : work.getCrumbsCatalogOfTools()) {
                toolsNames.add(tool.getName());
            }
        }
        uiWork.setToolList(toolsNames);
        uiWork.setWorkDescription(work.getWorkDescription());
        uiWork.setWorkName(work.getWorkname());
        uiWork.setParent(work.isIsParent());
        uiWork.setDelete(work.isDelete());

        /*List<UICrumbsWorkItem> children=new ArrayList<UICrumbsWorkItem>();
        for (CrumbsCatalogOfWork crumbsCatalogOfWork:work.getCrumbsCatalogOfWorks()){
            children.add(Proxy.getInstance().createFromCatalogOfWorks(crumbsCatalogOfWork));
        }
        uiWork.setChildren(children);   */

        return uiWork;
    }

    public CrumbsCatalogOfWork createCatalogOfWorks(UICrumbsWorkItem uiWork) {
        DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
        CrumbsCatalogOfWork workItem = new CrumbsCatalogOfWork();
        try {
            workItem.setDelete(uiWork.isDelete());
            workItem.setId(uiWork.getId());
            workItem.setWorkname(uiWork.getWorkName());
            workItem.setWorkDescription(uiWork.getWorkDescription());
            workItem.setRuntime(uiWork.getRuntime());
            workItem.setIsParent(uiWork.isParent());

            CrumbsCatalogOfWork parent = factory.getCrumbsCatalogOfWorkDAO().getById(uiWork.getParentId());
            workItem.setCrumbsCatalogOfWork(parent);

            Set<CrumbsCatalogOfTools> tools = new HashSet<CrumbsCatalogOfTools>();
            //Set<CrumbsCatalogOfTools> allTools = (Set<CrumbsCatalogOfTools>) factory.getCrumbsCatalogOfToolsDAO().getAll();
            ArrayList<CrumbsCatalogOfTools> allTools = (ArrayList<CrumbsCatalogOfTools>) factory.getCrumbsCatalogOfToolsDAO().getAll();
            if (uiWork.getToolList() != null) {
                for (String selectedToolName : uiWork.getToolList()) {
                    for (CrumbsCatalogOfTools tool : allTools) {
                        if (selectedToolName.equals(tool.getName()))
                            tools.add(tool);
                    }
                }
            }
            if (tools != null) {
                workItem.setCrumbsCatalogOfTools(tools);
            }
            //no worklist!
        } catch (Exception e) {
            e.printStackTrace();
        }
        return workItem;
    }

    public UICrumbsToolItem createFromCatalogOfTools(CrumbsCatalogOfTools tool) {
        UICrumbsToolItem uiTool = new UICrumbsToolItem();
        uiTool.setId(tool.getId());
        uiTool.setToolName(tool.getName());
        ArrayList<String> workList = new ArrayList<String>();
        if ((tool.getCrumbsCatalogOfWorks()) != null)

            for (CrumbsCatalogOfWork work : tool.getCrumbsCatalogOfWorks()) {
                workList.add(work.getWorkname());
            }
        uiTool.setWorkList(workList);
        uiTool.setDelete(tool.isDelete());
        uiTool.setToolsDescription(tool.getToolsDescription());
        return uiTool;
    }

    public CrumbsCatalogOfTools createCatalogOfTools(UICrumbsToolItem uiTool) {
        CrumbsCatalogOfTools tool = new CrumbsCatalogOfTools();
        DAOFactory factory = SpringBeansFactory.getInstance().getBeanByClass(DAOFactory.class);
        try {
            //if (uiTool.getId()!=0)
            tool.setId(uiTool.getId());
            tool.setName(uiTool.getToolName());
            tool.setToolsDescription(uiTool.getToolsDescription());
            tool.setDelete(uiTool.isDelete());
            //ArrayList<CrumbsCatalogOfWork> workList = new ArrayList<CrumbsCatalogOfWork>();
            Set<CrumbsCatalogOfWork> workList = new HashSet<CrumbsCatalogOfWork>();
            ArrayList<CrumbsCatalogOfWork> allWorks = new ArrayList<CrumbsCatalogOfWork>();
            allWorks.addAll(factory.getCrumbsCatalogOfWorkDAO().getAll());
            for (String workName : uiTool.getWorkList()) {
                for (CrumbsCatalogOfWork work : allWorks) {
                    if (work.getWorkname().equals(workName))
                        workList.add(work);
                }
            }
            tool.setCrumbsCatalogOfWorks(workList);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return tool;
    }

    public UICrumbsDateAndTime createFromCumbsDateAndTime(CrumbsDateAndTime dateAndTime) {
        UICrumbsDateAndTime uiDateAndTime = new UICrumbsDateAndTime();
        uiDateAndTime.setId(dateAndTime.getId());
        uiDateAndTime.setDateBegin(dateAndTime.getDateBegin());
        uiDateAndTime.setDateEnd(dateAndTime.getDateEnd());
        uiDateAndTime.setAssignedTimeBegin(dateAndTime.getAssignedTimeBegin());
        uiDateAndTime.setAssignedTimeEnd(dateAndTime.getAssignedTimeEnd());
        return uiDateAndTime;
    }


}
